package com.epalmpay.service.activity.impl;

import javax.annotation.Resource;

import com.epalmpay.dto.activity.*;
import com.epalmpay.dto.mall.MallGoodOutDTO;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.service.groupaccount.IGroupAccountService;
import com.epalmpay.util.Const;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import com.epalmpay.bean.CouponBean;
import com.epalmpay.enumdef.ActivityEnum.CouponStatus;
import com.epalmpay.enumdef.ActivityEnum.CouponType;
import com.epalmpay.enumdef.ActivityEnum.CouponValidType;
import com.epalmpay.enumdef.ActivityEnum.ExchangePlaceType;
import com.epalmpay.service.activity.IActivityCouponService;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.Tools;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.*;


@Service("activityCouponService")
public class ActivityCouponServiceImpl implements IActivityCouponService {
	
	@Resource  
    private CouponMapper couponMapper;
	@Resource  
    private ActivityBaseMapper activityBaseMapper;
	@Resource  
    private CouponUserMapper couponUserMapper;
	@Resource
	private GroupAccountMapper groupAccountMapper;
	@Resource
	private GroupAccountLogMapper groupAccountLogMapper;

	@Resource
	private IGroupAccountService groupAccountService;

	@Resource(name="transactionManager")
	private DataSourceTransactionManager transactionManager;

	@Resource
	private MallEntityGoodMapper mallEntityGoodMapper;
	@Resource
	private CouponGoodsShareMapper couponGoodsShareMapper;

	@Resource
	private CouponActivityShareMapper couponActivityShareMapper;
	@Resource
	private MallGoodMapper mallGoodMapper;





	public List<CouponOutDTO> getCouponList(CouponInDTO couponInDTO,Page page) throws Exception{
		
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", couponInDTO.getGroupId());
		param.put("purposeType", couponInDTO.getPurposeType());
		param.put("couponType", couponInDTO.getCouponType());
		param.put("couponStatus", couponInDTO.getCouponStatus());
		param.put("exchangePlaceType", couponInDTO.getExchangePlaceType());
		param.put("name", couponInDTO.getName());
		param.put("getType", couponInDTO.getGetType());
		
		List<CouponOutDTO> result = new ArrayList<CouponOutDTO>();

		int sumCount = couponMapper.selectCouponListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return null;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<Coupon> couponList = couponMapper.selectCouponList(param);
		
		for (Coupon coupon : couponList) {
			CouponOutDTO couponOutDTO = new CouponOutDTO();			
			PropertyCopyUtil.copyPropertiesExclude(coupon,couponOutDTO);
			//兑换地点处理
			if(Tools.isEmpty(couponOutDTO.getShopids()))
				couponOutDTO.setExchangePlaceType(ExchangePlaceType.AllShop.getType());
			else
				couponOutDTO.setExchangePlaceType(ExchangePlaceType.LimitedShop.getType());
			
			result.add(couponOutDTO);
		}
		
		return result;
	}

	public CouponListOutDTO getCouponList(CouponInDTO couponInDTO) throws Exception{

		CouponListOutDTO result = new CouponListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", couponInDTO.getGroupId());
		param.put("purposeType", couponInDTO.getPurposeType());
		param.put("couponType", couponInDTO.getCouponType());
		param.put("couponStatus", couponInDTO.getCouponStatus());
		param.put("exchangePlaceType", couponInDTO.getExchangePlaceType());
		param.put("name", couponInDTO.getName());
		param.put("getType", couponInDTO.getGetType());

		int sumCount = couponMapper.selectCouponListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", couponInDTO.getPageSize());
		param.put("start", couponInDTO.getPageSize()*(couponInDTO.getPageNo()-1));

		List<Coupon> couponList = couponMapper.selectCouponList(param);
        List<CouponOutDTO> couponOutDTOList = new ArrayList<CouponOutDTO>();

		for (Coupon coupon : couponList) {
			CouponOutDTO couponOutDTO = new CouponOutDTO();
			PropertyCopyUtil.copyPropertiesExclude(coupon,couponOutDTO);
			//兑换地点处理
			if(Tools.isEmpty(couponOutDTO.getShopids()))
				couponOutDTO.setExchangePlaceType(ExchangePlaceType.AllShop.getType());
			else
				couponOutDTO.setExchangePlaceType(ExchangePlaceType.LimitedShop.getType());
			couponOutDTOList.add(couponOutDTO);
		}
		if(couponOutDTOList.size()>0)
			result.setCouponOutDTOList(couponOutDTOList);

		return result;
	}

	public List<CouponOutDTO> getCouponListByShopId(CouponInDTO couponInDTO,Page page) throws Exception{
		
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", couponInDTO.getGroupId());
		//param.put("purposeType", couponInDTO.getPurposeType());
		param.put("couponType", couponInDTO.getCouponType());
		param.put("couponStatus", couponInDTO.getCouponStatus());
		//param.put("exchangePlaceType", couponInDTO.getExchangePlaceType());
		param.put("shopId", couponInDTO.getShopId());
		param.put("name", couponInDTO.getName());
		//param.put("getType", couponInDTO.getGetType());
		param.put("exchangePlace", ActivityEnum.ActivityPlatformType.OffLine.getType());

		
		List<CouponOutDTO> result = new ArrayList<CouponOutDTO>();

		int sumCount = couponMapper.selectCouponListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return null;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<Coupon> couponList = couponMapper.selectCouponList(param);
		
		for (Coupon coupon : couponList) {
			CouponOutDTO couponOutDTO = new CouponOutDTO();			
			PropertyCopyUtil.copyPropertiesExclude(coupon,couponOutDTO);
			//兑换地点处理
			//if(Tools.isEmpty(couponOutDTO.getShopids()))
			//	couponOutDTO.setExchangePlaceType(ExchangePlaceType.AllShop.getType());
			//else
			//	couponOutDTO.setExchangePlaceType(ExchangePlaceType.LimitedShop.getType());
			
			result.add(couponOutDTO);
		}
		
		return result;
	}

    public List<CouponOutDTO> GetSpecialActivityCouponList(CouponInDTO couponInDTO) throws Exception{

        Map<String,Object> param=new HashMap<String,Object>();
        param.put("groupID", couponInDTO.getGroupId());
        param.put("purposeType", couponInDTO.getPurposeType());
        param.put("status", ActivityEnum.CouponStatus.Getting.getType());

        List<CouponOutDTO> result = new ArrayList<CouponOutDTO>();

        List<Coupon> couponList = couponMapper.GetSpecialActivityCouponList(param);

        for (Coupon coupon : couponList) {
            CouponOutDTO couponOutDTO = new CouponOutDTO();
            PropertyCopyUtil.copyPropertiesExclude(coupon,couponOutDTO);
            //兑换地点处理
            if(Tools.isEmpty(couponOutDTO.getShopids()))
                couponOutDTO.setExchangePlaceType(ExchangePlaceType.AllShop.getType());
            else
                couponOutDTO.setExchangePlaceType(ExchangePlaceType.LimitedShop.getType());

            result.add(couponOutDTO);
        }

        return result;
    }
    
    public int  saveCoupon(CouponAddInDTO couponAddInDTO,String url) throws Exception{
    	
    	int result = 0;
		Integer freezeAmount = 0;
		Boolean autoAddFlag = Boolean.FALSE;

    	Coupon record = new Coupon();
    	if(couponAddInDTO.getValidTimeType() == CouponValidType.FixedTime.getType()){
    		couponAddInDTO.setDays(null);
    	}
    	if(couponAddInDTO.getSettedMode() == 2){//门店结算
    		couponAddInDTO.setSettedValue(0);
    	}else if(couponAddInDTO.getSettedMode() == 1) {
    		//服务商品 ，设置的渠道承担， 设置他的结算金额 等于面额
    		if(couponAddInDTO.getSettedValue()==null){
    			couponAddInDTO.setSettedValue(couponAddInDTO.getValue()*100);//面值
    		}
    	}
    	if(couponAddInDTO.getCouponType() == CouponType.FullSubCoupon.getType()){//满减券
    		couponAddInDTO.setValue(couponAddInDTO.getValue()*100);//面值
    		couponAddInDTO.setGoodsId(null);//商品id不为空
    		if(couponAddInDTO.getVerifyReadd() == 1)//不允许
    			couponAddInDTO.setVerifyReaddCount(-1);//核销叠加

			//服务商品总部结算 或者 商城商品时进行营销账户冻结金额计算
			if((couponAddInDTO.getGoodType() == CommonEnum.GoodType.Service.getType() && couponAddInDTO.getSettedMode() ==1) ||
					couponAddInDTO.getGoodType() == CommonEnum.GoodType.Goods.getType()) {
				if(couponAddInDTO.getTotalCount()==null||couponAddInDTO.getTotalCount()==0) {
					freezeAmount = Const.COUPON_FREEZE_AMOUNT;
					autoAddFlag = Boolean.TRUE;
				}else{
					freezeAmount =  (couponAddInDTO.getSettedValue() == null ? couponAddInDTO.getValue() : couponAddInDTO.getSettedValue()) * couponAddInDTO.getTotalCount();
				}
			}
    	}    	
    	else if(couponAddInDTO.getCouponType() == CouponType.DiscountCoupon.getType()){//打折券
    		couponAddInDTO.setValue(couponAddInDTO.getDiscountRate());//前端已经*100
    		couponAddInDTO.setVerifyReaddCount(null);//核销叠加
    	}
//    	else if(couponAddInDTO.getCouponType() == CouponType.GoodCoupon.getType()){//商品券
//    		couponAddInDTO.setValue(null);//面值
//    		couponAddInDTO.setVerifyReaddCount(null);//核销叠加
//    		couponAddInDTO.setExchangePlace(null);//券兑换地点(平台类型枚举 线上或线下)
//    		couponAddInDTO.setSettedValue(null);//结算金额
//    	}
    	
    	PropertyCopyUtil.copyPropertiesExclude(couponAddInDTO,record);
    	record.setGmtCreate(new Date());
    	record.setGmtModified(new Date());
    	record.setStatus(CouponStatus.Getting.getType());
    	record.setCreator(couponAddInDTO.getLoginId());
		record.setSumAmount(freezeAmount);
		record.setAutoAddFlag(autoAddFlag);
		record.setVerifiedCount(0);
		if(couponAddInDTO.getGetType() !=null && couponAddInDTO.getGetType()==2){
			record.setShareGoods(couponAddInDTO.getGoodids());
		}
		//判断如果发行量为0那么存入数据库时为-1 表示不限
		if (record.getTotalCount() == 0){
			record.setTotalCount(-1);
		}
    	result = couponMapper.insert(record);

		if(couponAddInDTO.getGetType() !=null && couponAddInDTO.getGetType()==4){
			Coupon coupon = new Coupon();
			coupon.setId(record.getId());
			if(couponAddInDTO.getGetLink()!=null&&couponAddInDTO.getGetLink()==1){//生成领取链接
					coupon.setGmtModified(new Date());
				//	String linkUrl="http://sbs-test.eboss007.com/2/coupon_full_detail.html?id="+record.getId();
					String linkUrl=url+"/api/oAuth2/getDiscount?id="+record.getId()+"&"+"groupId="+couponAddInDTO.getGroupId()+"&type=1";
					coupon.setLink(linkUrl);
				}
			
			if(couponAddInDTO.getGetQrcode()!=null&&couponAddInDTO.getGetQrcode()==1){//生成二维码
				String qrcodeUrl=url+"/api/oAuth2/getDiscount?id="+record.getId()+"&"+"groupId="+couponAddInDTO.getGroupId()+"&type=1";
				coupon.setQrcode(qrcodeUrl);
			}
			if(couponAddInDTO.getGetLink()!=null  || couponAddInDTO.getGetQrcode()!=null){
				couponMapper.updateByPrimaryKeySelective(coupon);
			}
		}
		//指定商品分享优惠券
		if(couponAddInDTO.getGetType() !=null && couponAddInDTO.getGetType()==2){
//			String  goodids="";
			CouponGoodsShare couponGoodsShare = new CouponGoodsShare();
			String[] ids = couponAddInDTO.getGoodids().split(",");
			for(int i= 0 ;i<ids.length;i++){
				String[] str = ids[i].split("/");
				for(int j=0;j<str.length;j++){
					couponGoodsShare.setGoodId(Long.parseLong(str[0]));
					couponGoodsShare.setGoodType(Integer.parseInt(str[1]));
				}
				couponGoodsShare.setGmtModified(new Date());
				couponGoodsShare.setCouponId(record.getId());
				couponGoodsShare.setGmtCreate(new Date());
				couponGoodsShareMapper.insertSelective(couponGoodsShare);
			}
//			goodids.substring(0,goodids.length()-1);
			record.setShareGoods(couponAddInDTO.getGoodids());
		}
		//指定活动分享优惠券
		if(couponAddInDTO.getGetType() !=null && couponAddInDTO.getGetType()==3){

			CouponActivityShare couponActivityShare = new CouponActivityShare();
			String[] ids = couponAddInDTO.getShareActivities().split(",");
			for(int i= 0 ;i<ids.length;i++){
				couponActivityShare.setGmtModified(new Date());
				couponActivityShare.setCouponId(record.getId());
				couponActivityShare.setActivityId(Long.parseLong(ids[i]));
				couponActivityShare.setGmtCreate(new Date());
				couponActivityShareMapper.insertSelective(couponActivityShare);
			}
		}




		//异业联盟优惠券不处理营销账户
    	if(couponAddInDTO.getPurposeType() != ActivityEnum.PurposeType.otherCoupon.getType()) {
			//增加营销账户冻结金额
			groupAccountService.updateAmount(couponAddInDTO.getGroupId(),
					BizEnum.SaleAccountSubjectType.CouponCreate, freezeAmount, record.getId(), null, null);
		}
    	return result;
    }
    
    //取得首页数据
    public CouponListOutDTO  getToIndexData(CouponInDTO couponInDTO) throws Exception{
    	CouponListOutDTO result = new CouponListOutDTO();
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("groupId", couponInDTO.getGroupId());
        
        Map<String,Object> selectResultMap = couponMapper.getIndexData(param);
        result.setRoutineNum((Integer.parseInt(selectResultMap.get("routine_num").toString())));
        result.setUnroutineNum((Integer.parseInt(selectResultMap.get("unroutine_num").toString())));
        result.setMemberNum((Integer.parseInt(selectResultMap.get("member_num").toString())));
    	return result;
    }
    
    public CouponDetailOutDTO  getCouponDetail(CouponInDTO couponInDTO,Page page) throws Exception{
    	CouponDetailOutDTO result = new CouponDetailOutDTO();
    	
    	Coupon coupon =  couponMapper.selectCouponDetailById(couponInDTO.getId());
    	if(coupon.getQrcode()!=null){
			String st_fname=coupon.getQrcode().replaceAll("&","%26");
			coupon.setQrcode(st_fname); 
		}

    	CouponOutDTO couponOutDTO = new CouponOutDTO();
    	PropertyCopyUtil.copyPropertiesExclude(coupon,couponOutDTO);

    	//如果登录门店ID不为空，表示是门店的优惠券信息查询，获取该门店优惠券的已核销数量
		if (couponInDTO.getLoginShopId()!=null) {
			Map<String,Object> shopParam=new HashMap<String,Object>();
			shopParam.put("couponId",couponInDTO.getId());
			shopParam.put("couponUseStatus",1);//优惠券已核销的状态
			shopParam.put("loginShopId",couponInDTO.getLoginShopId());//登录的门店ID，当前门店ID
			couponOutDTO.setShopVerifiedCount(couponUserMapper.selectCouponUserListCount(shopParam));
		}

		result.setCouponOutDTO(couponOutDTO);
    	
    	//取得关联活动名称
    	Map<String,Object> param=new HashMap<String,Object>();
        param.put("couponId", couponInDTO.getId());
        result.setActivityBaseList(activityBaseMapper.selectActiityByCouponId(param));
    	
        //取得优惠券使用记录
        param.clear();
        param.put("couponId", couponInDTO.getId());
		param.put("couponUseStatus", couponInDTO.getCouponUseStatus());
        param.put("loginShopId",couponInDTO.getLoginShopId());
        param.put("startDate", couponInDTO.getStartDate());
        param.put("endDate", couponInDTO.getEndDate());
        param.put("name", couponInDTO.getName());
        
		int sumCount = couponUserMapper.selectCouponUserListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount>0){
			param.put("limit", page.getShowCount());
			param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
			result.setCouponUserDTOList(couponUserMapper.selectCouponUserList(param));
		}
    	return result;
    }

	public Coupon queryCouponById(Coupon coupon) throws Exception {

		return couponMapper.selectByPrimaryKey(coupon.getId());
	}

	public void updateCoupon(Coupon coupon) {
		couponMapper.updateByPrimaryKeySelective(coupon);
	}

	public void updateCoupon(CouponInDTO couponInDTO) throws Exception {
		Coupon oldRecord = couponMapper.selectByPrimaryKey(couponInDTO.getId());
		oldRecord.setSettedValue(oldRecord.getSettedValue()==null?0:oldRecord.getSettedValue());
        Integer addTotalCount = 0;
		Integer freezeAmount = 0;

		Coupon record = new Coupon();
		record.setId(couponInDTO.getId());
		record.setGmtModified(new Date());
		record.setName(couponInDTO.getName());
		record.setTotalCount(couponInDTO.getTotalCount());
		record.setAmountPeruser(couponInDTO.getAmountPeruser());
		if(oldRecord.getValidTimeType() == ActivityEnum.ValidTimeType.FixedTime.getType())
			record.setValidEndTime(couponInDTO.getValidEndTime());
		addTotalCount = record.getTotalCount() - oldRecord.getTotalCount();
		if(oldRecord.getCouponType() == CouponType.FullSubCoupon.getType()){//满减券
			//计算冻结金额
			freezeAmount =  oldRecord.getSettedValue()	* addTotalCount;
			record.setSumAmount(oldRecord.getSumAmount()==null?0:oldRecord.getSumAmount() + freezeAmount);
		}
		couponMapper.updateByPrimaryKeySelective(record);

		//追加冻结金额
		if(freezeAmount<=0)
			return;

		//增加营销账户冻结金额
		groupAccountService.updateAmount(couponInDTO.getGroupId(),
				BizEnum.SaleAccountSubjectType.CouponCreate,freezeAmount,record.getId(),null,"优惠券增加数量");
	}


	public void endCouponStatus(Long couponId) throws Exception{
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		try {
			Coupon record = new Coupon();
			record.setId(couponId);
			record.setGmtModified(new Date());
			record.setStatus(CouponStatus.Over.getType());//结束2
			couponMapper.updateByPrimaryKeySelective(record);

			record = couponMapper.selectByPrimaryKey(record.getId());

			//处理满减券的解冻金额
			if (record.getCouponType() == CouponType.FullSubCoupon.getType()) {//满减券
				Integer unfreezeAmount = 0;
				//计算解冻金额
				record.setTotalCount(record.getTotalCount() == null ? 0 : record.getTotalCount());
				record.setVerifiedCount(record.getVerifiedCount() == null ? 0 : record.getVerifiedCount());
				record.setSettedValue(record.getSettedValue() == null ? 0 : record.getSettedValue());
				unfreezeAmount = (record.getTotalCount() - record.getVerifiedCount()) * record.getSettedValue();
				if (unfreezeAmount > 0) {
					//解冻营销账户冻结金额
					groupAccountService.updateAmount(record.getGroupId(),
							BizEnum.SaleAccountSubjectType.CouponUnfreeze, unfreezeAmount, record.getId(), null, null);
				}
			}
			transactionManager.commit(status);
		}catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}
		return;
	}

	//结束过期的优惠券
	public void endExpireAllCoupon() throws Exception{
		List<Coupon> coupons = couponMapper.selectExpireCouponList();
		for(Coupon coupon:coupons){
			endCouponStatus(coupon.getId());
		}
	}



	public void updateShop(Coupon coupon) {
		couponMapper.updateByPrimaryKeySelective(coupon);
	}


	public List<Map<String, Object>> getCouponListById(List<Long> couponIdSet) {
		return couponMapper.getCouponListById(couponIdSet);
	}

	public List<Map<String, Object>> getCouponListById(Set<Long> couponIdSet) {
		return couponMapper.getCouponSetById(couponIdSet);
	}


	public List<CouponBean> couponList(Coupon coupon) {
//		coupon.setTodayTime(new Date());
		coupon.setStatus(ActivityEnum.CouponStatus.Getting.getType());
		return couponMapper.couponList(coupon);
	}


	public Coupon findById(CouponInDTO couponInDTO) {
		return couponMapper.findById(couponInDTO.getCouponId());
	}

//	//优惠券核销
//	public int updateVerifyCoupon(String couponCode,Long shopId,String orderNo,Long orderId) throws Exception{
//		int result =0;
//
//		if (Tools.isEmpty(couponCode)) {
//			throw new ApplicationException(Rescode.FAIL, "couponCode 不能为空！");
//		}
//		if (shopId == null || shopId <= 0) {
//			throw new ApplicationException(Rescode.FAIL, "shopId 不能为空！");
//		}
//
//		CouponUser couponUser = couponUserMapper.selectByCouponSn(couponCode);
//		if(couponUser.getCouponUseStatus() != ActivityEnum.CouponUseStatus.Received.getType() && couponUser.getCouponUseStatus() != ActivityEnum.CouponUseStatus.locked.getType()){
//			throw new ApplicationException(Rescode.FAIL, "优惠券状态不正确，不能核销！");
//		}
//		if((new Date()).compareTo(couponUser.getValidTime())>0){
//			throw new ApplicationException(Rescode.FAIL, "优惠券已过有效期，不能核销！");
//		}
//
//		//更新coupon_user表
//		CouponUser updateCouponUser = new CouponUser();
//		updateCouponUser.setId(couponUser.getId());
//		updateCouponUser.setGmtModified(new Date());
//        updateCouponUser.setVerifyTime(new Date());
//        updateCouponUser.setCouponUseStatus(ActivityEnum.CouponUseStatus.Verified.getType());
//        updateCouponUser.setShopId(shopId);
//        updateCouponUser.setOrderNo(orderNo);
//        updateCouponUser.setOrderId(orderId);
//        result = couponUserMapper.updateByPrimaryKeySelective(updateCouponUser);
//        //更新coupon表
//		result = couponMapper.updateHaveVerifyCountByCouponId(couponUser.getCouponId());
//
//		//更新营销账户
//		Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
//		//异业联盟优惠券不处理营销账户
//		if(coupon.getPurposeType() != ActivityEnum.PurposeType.otherCoupon.getType()) {
//			result = groupAccountService.updateAmount(couponUser.getGroupId(), BizEnum.SaleAccountSubjectType.CouponGet,
//					coupon.getValue(), couponUser.getId(), null, null);
//		}
//		return result;
//	}

	@Override
	public int updateVerifyCoupon(String couponCode,Long shopId, TradeOffline tradeOffline) throws Exception{
		int result =0;

		if (shopId == null || shopId <= 0) {
			throw new ApplicationException(Rescode.FAIL, "shopId 不能为空！");
		}
        if(StringUtils.isNotBlank(couponCode)){
        	CouponUser couponUser=couponUserMapper.selectByCouponSn(couponCode);
        	 finishUpdateVerifyCoupon(couponUser, shopId, tradeOffline);
        }else{
        	List<CouponUser> couponUsers = couponUserMapper.selectByOrderNo(tradeOffline.getOrderId());
    		for(CouponUser couponUser:couponUsers){
    			finishUpdateVerifyCoupon(couponUser, shopId, tradeOffline);
    		}
        }
		
		return result;
		
	}



	private void finishUpdateVerifyCoupon(CouponUser couponUser,Long shopId, TradeOffline tradeOffline) throws Exception {
		int result=0;
		if(couponUser.getCouponUseStatus() != ActivityEnum.CouponUseStatus.Received.getType() && couponUser.getCouponUseStatus() != ActivityEnum.CouponUseStatus.locked.getType()){
			throw new ApplicationException(Rescode.FAIL, "优惠券状态不正确，不能核销！");
		}
		if(couponUser.getValidTime()!=null){
			if((tradeOffline.getGmtCreate()).compareTo(couponUser.getValidTime())>0){
				throw new ApplicationException(Rescode.FAIL, "优惠券已过有效期，不能核销");
			}
		}
		
		//更新coupon_user表
		CouponUser updateCouponUser = new CouponUser();
		updateCouponUser.setId(couponUser.getId());
		updateCouponUser.setGmtModified(new Date());
        updateCouponUser.setVerifyTime(new Date());
        updateCouponUser.setCouponUseStatus(ActivityEnum.CouponUseStatus.Verified.getType());
        updateCouponUser.setShopId(shopId);
        updateCouponUser.setOrderId(tradeOffline.getId());
        updateCouponUser.setOrderNo(tradeOffline.getOrderId());
        updateCouponUser.setMemberId(tradeOffline.getPayerId());
        result = couponUserMapper.updateByPrimaryKeySelective(updateCouponUser);
        //更新coupon表
		result = couponMapper.updateHaveVerifyCountByCouponId(couponUser.getCouponId());

		//更新营销账户
		Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
		result = groupAccountService.updateAmount(couponUser.getGroupId(), BizEnum.SaleAccountSubjectType.CouponGet,
				coupon.getValue(), couponUser.getId(), null, null);
	}


	@Override
	public CouponListOutDTO getShareGoodListById(CouponAddInDTO couponAddInDTO) {
		CouponListOutDTO couponListOutDTO = new CouponListOutDTO();

		String[] ids = couponAddInDTO.getShareGoods().split(",");

		String mallGoodIds="";
		String EntutymallGoodIds="";
		for(int i= 0 ;i<ids.length;i++){
			String[] str = ids[i].split(":");
			for(int j=0;j<str.length-1;j++){
				if(str[1].equals("1")){
					mallGoodIds +=str[0];
					mallGoodIds +=",";
				}else{
					EntutymallGoodIds +=str[0];
					EntutymallGoodIds +=",";
				}
			}
		}
		List<MallGoodOutDTO> list1 = new ArrayList<MallGoodOutDTO>();
		List<MallGoodOutDTO> list2 = new ArrayList<MallGoodOutDTO>();
		if(mallGoodIds!=""){
			String[] mallGoodIdString = mallGoodIds.substring(0, mallGoodIds.length() - 1).split(",");
			for(int i=0;i<mallGoodIdString.length;i++){
				MallGoodOutDTO mallGoodOutDTO = mallGoodMapper.queryMallGoodNameById(mallGoodIdString[i]);
				list1.add(mallGoodOutDTO);
			}
		}
		if(EntutymallGoodIds !=""){
			String[] EntutymallGoodIdString = EntutymallGoodIds.substring(0, EntutymallGoodIds.length() - 1).split(",");
			for(int i=0;i<EntutymallGoodIdString.length;i++){
				MallGoodOutDTO mallGoodOutDTO = mallEntityGoodMapper.queryMallEntityGoodById(EntutymallGoodIdString[i]);
				list2.add(mallGoodOutDTO);
			}
		}
		list1.addAll(list2);

		couponListOutDTO.setMallGoodOutDTOList(list1);
		return couponListOutDTO;
	}

	@Override
	public CouponListOutDTO getActivityListById(CouponAddInDTO couponAddInDTO) {
		CouponListOutDTO couponListOutDTO = new CouponListOutDTO();
		String[] ids = couponAddInDTO.getShareActivities().split(",");
		List<ActivityBaseOutDTO> list1 = new ArrayList<ActivityBaseOutDTO>();
		for(int i=0;i<ids.length;i++){
			ActivityBaseOutDTO activityBaseOutDTO =activityBaseMapper.queryActivityNameById(ids[i]);
			list1.add(activityBaseOutDTO);
		}
		couponListOutDTO.setActivityBaseOutDTOList(list1);
		return couponListOutDTO;
	}




}
